package xm.erzhan.handlers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xm.erzhan.models.UserEntity;
import xm.erzhan.models.responseModels.UserRes;
import xm.erzhan.repository.UserRepository;
import xm.erzhan.utils.Utils;
import xm.erzhan.controllers.UserController;


@Controller
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserHandler {
    @Autowired
    private UserRepository userRepository;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public  @ResponseBody UserRes login(@RequestBody UserEntity userReq) {
        String reqUserName = userReq.getUserName();
        String reqPassWord = userReq.getPassWord();


        // find user in server cache
        UserController userController = UserController.UserControllerShared();
        UserEntity userInfo = userController.getUserByUserName(reqUserName);
        if (userInfo != null) {
            String userStr = userInfo.getUserName();
            String pwdStr = userInfo.getPassWord();

            // handle and response
            if (userStr.equals(reqUserName) && pwdStr.equals(reqPassWord)) {

                String encode = Utils.AESEncode(reqUserName + "|" + reqPassWord);

                UserRes response = new UserRes(200, encode);

                return response;

            }

            UserRes response = new UserRes(500, "userName of passWord error");

            return response;

        }


        UserEntity userEntity = userRepository.findUserByUserName(reqUserName);

        if (userEntity == null) {
            UserRes response = new UserRes(500, "userName of passWord error");
            return response;
        }

        userController.setUserSet(userEntity);


        String user = userEntity.getUserName();
        String pwd = userEntity.getPassWord();

        // handle and response
        if (user.equals(reqUserName) && pwd.equals(reqPassWord)) {


            String encode = Utils.AESEncode(reqUserName + "|" + reqPassWord);

            Long nowTime = Utils.getTimeNow();

            userEntity.setLastLoginTime(nowTime);

            userRepository.saveAndFlush(userEntity);

            UserRes response = new UserRes(200, encode);

            return response;

        } else  {
            UserRes response = new UserRes(500, "userName of passWord error");

            return response;
        }

    }
}
